package com.nd.android.u.ui.activity.chat_relative_quickreply;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.common.StarAppConst;
import com.common.utils.StarAppUtils;
import com.common.widget.CommonActivityTitle;
import com.common.widget.CommonActivityTitle.TitleBtnCallback;
import com.nd.android.u.allCommonUtils.ToastUtils;
import com.nd.android.u.business.db.dao.QuickReplyDao;
import com.nd.android.u.controller.bean.QuickReply;
import com.nd.android.u.controller.bean.QuickReplyList;
import com.nd.android.u.controller.factory.ChatDaoFactory;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.widge.DragListViewController;
import com.nd.android.u.ui.widge.DragListViewController.onEventListener;
import com.product.android.ui.activity.BaseReceiverFragmentActivity;

public class QuickReplyAcitivty extends BaseReceiverFragmentActivity implements
		OnClickListener {
	private static final int SHOW_ADD = 0;
	private static final int SHOW_DEL = 1;
	private static final int FOOTER_VIEW_ID = 99;
	/** 顶部Title */
	private CommonActivityTitle mCommonActivityTitle;

	private Button btAdd;
	private Button btDel;
	private Button btModify;
	private EditText etText;
	private QuickReplyDao mQuickReplyDao;
	private QuickReplyList mQuickReplyList;
	private DragListViewController mDragListViewController;
	private QuickReplyAdapter mQuickReplyAdapter;
	private int mPosition = -1;
	private boolean mbIsResorted = false;
	private ListView lvQuickReply;
	private View mFooterView;

	/** 软键盘管理 */
	private InputMethodManager mInputMethodManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.quick_reply);
		initView();
	}

	private void initView() {
		mInputMethodManager = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		mCommonActivityTitle = (CommonActivityTitle) findViewById(R.id.common_activity_title);
		mCommonActivityTitle.setTitleTextTypeface(StarAppConst.getInstance().getLTXTypeface(), false);
		mCommonActivityTitle.setTitleBtnCallback(new TitleBtnCallback() {
			@Override
			public void onBtnClick(int clickType) {
				finish();
			}
		});

		btAdd = (Button) findViewById(R.id.btAdd);
		btDel = (Button) findViewById(R.id.btDel);
		btModify = (Button) findViewById(R.id.btModify);
		etText = (EditText) findViewById(R.id.etText);
		StarAppUtils.setViewTypeFace(btAdd, false);
		StarAppUtils.setViewTypeFace(btDel, false);
		StarAppUtils.setViewTypeFace(btModify, false);
		StarAppUtils.setViewTypeFace(etText, false);
		// TextView tvTitle = (TextView) findViewById(R.id.header_text_title);
		// tvTitle.setGravity(Gravity.CENTER);
		// tvTitle.setText(R.string.quick_reply);
		// findViewById(R.id.header_btn_left).setOnClickListener(this);
		// findViewById(R.id.header_layout_right).setVisibility(View.INVISIBLE);
		btAdd.setOnClickListener(this);
		btDel.setOnClickListener(this);
		btModify.setOnClickListener(this);
		// 获取快捷回复
		getReplyTexts();
		lvQuickReply = (ListView) findViewById(R.id.lvQuickReply);
		mQuickReplyAdapter = new QuickReplyAdapter(this, mQuickReplyList);
		// 在listview的底部增加一个“添加快捷回复”的ITEM
		getFooterView();
		lvQuickReply.addFooterView(mFooterView);
		lvQuickReply.setAdapter(mQuickReplyAdapter);
		lvQuickReply.getAdapter();
		// 添加拖动控制
		mDragListViewController = new DragListViewController(this, lvQuickReply);
		mDragListViewController.manageList();
		mDragListViewController.setOnEventListener(listener);
		mbIsResorted = false;
		changeLayout(SHOW_ADD);
	}

	/**
	 * @n<b>函数名称</b> :getFooterView
	 * @brief 获取列表底部“添加快捷回复”的ITEM
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-7-9下午3:08:07
	 */
	private void getFooterView() {
		mFooterView = mQuickReplyAdapter.getFooterView();
		mFooterView.setTag(false);
		mFooterView.setId(FOOTER_VIEW_ID);
		mFooterView.setOnClickListener(this);
	}

	/**
	 * @n<b>函数名称</b> :removeFooterView
	 * @brief 移除“添加快捷回复”的ITEM
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-7-9下午3:08:32
	 */
	private void removeFooterView() {
		lvQuickReply.setAdapter(null);
		lvQuickReply.removeFooterView(mFooterView);
		lvQuickReply.setAdapter(mQuickReplyAdapter);
	}

	private onEventListener listener = new onEventListener() {
		@Override
		public void onSwitch(int from, int to) {
			if (from == to) {
				return;
			}
			// 交换位置
			mbIsResorted = true;
			mQuickReplyList.exchange(from, to);
			mQuickReplyAdapter.notifyDataSetChanged();
			// 改变布局
			changeLayout(SHOW_ADD);
		}

		@Override
		public void onClick(int position) {
			// 点击某个ITEM
			if (position >= 0 && position < mQuickReplyList.size()) {
				etText.setText(mQuickReplyList.get(position).getText());
				changeLayout(SHOW_DEL);
				etText.requestFocus();
				mPosition = position;
			}
		}
	};

	/**
	 * @n<b>函数名称</b> :getReplyTexts
	 * @brief 获取快捷回复列表
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-7-9下午3:09:20
	 */
	private void getReplyTexts() {
		mQuickReplyDao = ChatDaoFactory.getInstance().getQuickReplyDao();
		mQuickReplyList = mQuickReplyDao.getReply();
		if (mQuickReplyList == null || mQuickReplyList.size() == 0) {
			// 如果数据库里取出的数据是空的，使用默认的数据
			String[] defaults = getResources().getStringArray(
					R.array.quick_reply);
			mQuickReplyList = new QuickReplyList();
			for (int i = 0, len = defaults.length; i < len; i++) {
				QuickReply reply = new QuickReply();
				reply.setText(defaults[i]);
				reply.setOrder(i);
				mQuickReplyList.add(reply);
				mQuickReplyDao.insertReply(reply);
			}
		}

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btDel) {
			onDel();
		} else if (id == R.id.btAdd) {
			onAdd();
		} else if (id == R.id.btModify) {
			onModity();
		} else if (id == FOOTER_VIEW_ID) {
			changeLayout(SHOW_ADD);
		}
	}

	/**
	 * @n<b>函数名称</b> :onDel
	 * @brief 删除快捷回复
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-7-9下午3:10:04
	 */
	private void onDel() {
		if (mPosition > -1 && mPosition < mQuickReplyList.size()) {
			QuickReply quickReply = mQuickReplyList.get(mPosition);
			boolean result = mQuickReplyDao.deleteReply(quickReply);
			// 先把数据从数据库中删除，删除成功的话刷新listview
			if (result) {
				mPosition = -1;
				mQuickReplyList.remove(quickReply);
				mQuickReplyAdapter.notifyDataSetChanged();
				changeLayout(SHOW_ADD);
			} else {
				ToastUtils.display(this, R.string.quick_reply_del_fail);
			}
		}
	}

	/**
	 * @n<b>函数名称</b> :onAdd
	 * @brief 添加快捷回复
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-7-9下午3:10:39
	 */
	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	private void onAdd() {
		String text = etText.getText().toString().trim();
		// 判断文本是否合法
		if (isIllegalText(text)) {
			return;
		}
		// 先把数据添加到数据库中，添加成功的话刷新listview
		QuickReply quickReply = new QuickReply();
		quickReply.setText(text);
		quickReply.setOrder(mQuickReplyList.size());
		long result = mQuickReplyDao.insertReply(quickReply);
		if (result < 0) {
			ToastUtils.display(this, R.string.quick_reply_add_fail);
			return;
		}
		mQuickReplyList.add(quickReply);
		mQuickReplyAdapter.notifyDataSetChanged();
		// 隐藏键盘，清空编辑框
		mInputMethodManager.hideSoftInputFromWindow(etText.getWindowToken(), 0);
		etText.setText("");
	}

	/**
	 * @n<b>函数名称</b> :onModity
	 * @brief 修改快捷回复
	 * @see
	 * @since Ver 1.2
	 * @param
	 * @return void
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-7-9下午3:11:34
	 */
	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	private void onModity() {
		String text = etText.getText().toString().trim();
		// 判断文本是否合法
		if (isIllegalText(text) || mPosition < 0) {
			return;
		}
		QuickReply quickReply = mQuickReplyList.get(mPosition);
		quickReply.setText(text);
		if (!mbIsResorted) {
			// 未重新排序，直接更新数据
			long result = mQuickReplyDao.updateReply(quickReply);
			if (result < 0) {
				ToastUtils.display(this, R.string.quick_reply_modify_fail);
			} else {
				mQuickReplyAdapter.notifyDataSetChanged();
			}
		}
		mInputMethodManager.hideSoftInputFromWindow(etText.getWindowToken(), 0);
	}

	/**
	 * @n<b>函数名称</b> :isIllegalText
	 * @brief 判断文本是否合法：不空且和旧的数据不冲突
	 * @see
	 * @since Ver 1.2
	 * @param @param text
	 * @param @return
	 * @return boolean
	 * @<b>作者</b> : cb
	 * @<b>创建时间</b> : 2013-7-9下午3:12:09
	 */
	private boolean isIllegalText(String text) {
		if (TextUtils.isEmpty(text)) {
			ToastUtils.display(this, R.string.quick_reply_empty);
			return true;
		}
		if (mQuickReplyList.isExist(text)) {
			ToastUtils.display(this, R.string.quick_reply_add_repeat);
			return true;
		}
		return false;
	}

	private void changeLayout(int state) {
		if (state == SHOW_DEL) {
			// 显示带删除项的界面
			btAdd.setVisibility(View.GONE);
			btModify.setVisibility(View.VISIBLE);
			btDel.setVisibility(View.VISIBLE);
			int count = lvQuickReply.getFooterViewsCount();
			if (count == 0) {
				lvQuickReply.addFooterView(mFooterView);
				lvQuickReply.setAdapter(mQuickReplyAdapter);
			}
		} else {
			// 显示修改的界面
			btAdd.setVisibility(View.VISIBLE);
			btModify.setVisibility(View.GONE);
			btDel.setVisibility(View.GONE);
			etText.setText("");
			removeFooterView();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mbIsResorted) {
			// 为避免频繁更新数据库，在onPause的时候才对数据的重排进行写库
			mQuickReplyList.resort();
			for (QuickReply reply : mQuickReplyList) {
				long result = mQuickReplyDao.updateReply(reply);
				if (result < 0) {
					ToastUtils.display(this, R.string.quick_reply_modify_fail);
					break;
				}
			}
		}
	}

}
